'use strict'

const db = require('electron-db');
const path = require('path');

class DataStore {
  constructor(db_name){
    this.db_name = db_name
    this.db_location = path.join(__dirname, '');
  }
  // db exist ?
  db_exist(){
    try{
      if (db.valid(this.db_name, this.db_location)) {
        return true;
        }
    }
    catch(e){
      return false;
    }
  };

  //create db
  create_db(){
    if (!this.db_exist()){
      db.createTable(this.db_name, this.db_location, (succ, msg) => {
          // succ - boolean, tells if the call is successful
          // console.log("Success: " + succ);
          // console.log("Message: " + msg);
      //   })
    })
    }
  };
  //insert data
  insert_data(obj){
    if (this.db_exist()){
      db.insertTableContent(this.db_name, this.db_location, obj, (succ, msg) => {
        // succ - boolean, tells if the call is successful
      })
    } else {
      this.create_db();
      db.insertTableContent(this.db_name, this.db_location, obj, (succ, msg) => {
        // succ - boolean, tells if the call is successful
      })
    }
  };

  get_all_data(){
    let db_data = [];
    db.getAll(this.db_name, this.db_location, (succ, data) => {
  // succ - boolean, tells if the call is successful
  // data - array of objects that represents the rows.
    if (succ){
      db_data = data
    }
    })
    return db_data;
  };


  delete_data(id){
    db.deleteRow(this.db_name, this.db_location, {'id': id}, (succ, msg) => {
      console.log(msg);
    })
  };

  find_row(dic){
    let db_data = [];
    db.getRows(this.db_name, this.db_location, dic, (succ, result) => {
    if (succ){
      db_data = result
    }
  })
  return db_data;
};

}
module.exports = DataStore
